package com.kevin.epacms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.kevin.epacms.constant.CommonConstant;
import com.kevin.epacms.entity.Permission;
import com.kevin.epacms.mapper.PermissionMapper;
import com.kevin.epacms.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kevin.epacms.util.RedisUtil;
import com.kevin.epacms.util.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kevin
 * @since 2022-11-10
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Resource
    private RedisUtil redisUtil;
    @Override
    public Result getMenuByRid(Integer roleId) {
        String key = CommonConstant.ROLE_ID_PREFIX + roleId;
        String menuJson = redisUtil.get(key);
        if(StrUtil.isNotBlank(menuJson)){
            List<Permission> permissions = JSONUtil.toList(menuJson, Permission.class);
            return Result.ok(permissions);
        }
        List<Permission> permissions = baseMapper.getMenuByRid(roleId);
        if(Objects.nonNull(permissions)){
            redisUtil.set(key, permissions, 1L, TimeUnit.DAYS);
        }
        return Result.ok(permissions);
    }
}
